$(document).ready(init);
var tournament;

function init(){
    console.log("DOM ready");
    $('#larsClickTest').click(startTournament);
    $('#commitEdit').click(editGame);
}
    
function startTournament(){
    console.log("btnClicked");
    var stringArray = $("#tf_teilnehmer").val();
    stringArray = stringArray.split(";");
    tournament = createTournament(stringArray);
    fillEdit();
    viewHR();
    $('#editGame').show();
}

function reFill(){
    viewHR();
}

function viewHR(){
    $('#hauptrunde').empty();
    var insterion = "<h3>Hauptrunde:</h3><ul>";
    for(var i = 0; i < tournament.mainRound.length; i++){
        var gameIndex = tournament.gameList[tournament.mainRound[i]].number;
        if(gameIndex == null){
            gameIndex = i + 1;
        }
        insterion = insterion + "<li> Spiel Nummer: " + gameIndex + "<ul>";
        
        var player1 = tournament.gameList[tournament.mainRound[i]].player1;
        if(player1 > -1){
            player1 = tournament.competitorsList[player1].name;
        }
        else{
            player1 = "Freilos"
        }
        var player2 = tournament.gameList[tournament.mainRound[i]].player2;
        if(player2 > -1){
            player2 = tournament.competitorsList[player2].name;
        }
        else{
            player2 = "Freilos"
        }        
        insterion = insterion + "<li>" + player1 + " vs. " + player2 + "</li>";
        var ergebnis = Game.getScore(tournament.gameList[tournament.mainRound[i]]);
        if(ergebnis == "-1 : -1"){
            ergebnis = "N/A";
        }
        insterion = insterion +"<li>Ergebnis: " + ergebnis + "</li>"+ "</ul></li>";
    }
    insterion = insterion + "</ul>";
    $(insterion).appendTo("#hauptrunde");  
}

function fillEdit(){
    var insertion = "";
    for(var i = 0; i < tournament.mainRound.length; i++){
        var game = "Spiel " + (tournament.mainRound[i] + 1);
        $('#games').append(new Option(game, tournament.mainRound[i]));
    }
}

function editGame(){
    var erg1 = $('#scoreS1').val();
    var erg2 = $('#scoreS2').val();
    Tournament.setErgebnis($('#games').val(),erg1,erg2, tournament);
    reFill();
}
